import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import Login from '../views/user/Login.vue'
import Register from '../views/user/Register.vue'

Vue.use(VueRouter)

const routes = [
    {
        path: '/',
        redirect: '/login'
    }, {
        path: '/login',
        component: Login
    }, {
        path: '/register',
        component: Register
    }, {
        path: '/home',
        component: Home,
        redirect: '/summary',
        children: [
            {
                path: '/summary',
                component: () => import('../views/score/Summary.vue')
            }, {
                path: '/tree',
                component: () => import('../views/baseconfig/Tree.vue')
            }, {
                path: '/billboard',
                component: () => import('../views/baseconfig/Billboard.vue')
            }, {
                path: '/score',
                component: () => import('../views/score/Score.vue')
            }
        ]
    }

]

const router = new VueRouter({
    routes
})

// 为路由对象添加 beforeEach 导航守卫
router.beforeEach((to, from, next) => {
    // 如果用户访问登陆页，直接放行
    if (to.path === '/login' || to.path === '/register') return next();

    const token = window.sessionStorage.getItem('login_user_name');
    // 没有 token 强制跳转到登陆页面
    if (!token) return next('/login');
    next();
})

export default router
